<template>
  <div class="chart-box">
    <el-row class="line-row" v-loading="chartLoading">
      <chart
        style="width: 100%; height: 100%"
        :option="chartData"
        ref="barChart"
        auto-resize
      ></chart>
    </el-row>
  </div>
</template>

<script>
import nt from '../../../../../network'
import parseApi from '../../../../utils/parseApi'

 import _ from 'lodash'
import mixinOption from '../../../../utils/mixinOption'

export default {
  name: 'custom-report-component-chart-bar',
  props: {
    api: {},
    method: {
      type: String,
      default: 'get',
    },
    dataKey: {},
    mainTitle: {},
    time: {},
    componentData: {},
    changeSize: {},
    changeData: {},
    interval: {},
    mixinParam: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  computed: {
    chartData() {
      return this.commonBarOption
    },
  },
  data() {
    return {
      comInterval: 0,

      chartLoading: false,
      isDataReady: false,
      isReverse: false,
      unit: '',
      firstCategoryList: [],
      seriesStackList: [],
      blueColors: ['#419EFF', '#66B0FE', '#8BC3FD', '#B1D6FB', '#C6DFF8'],
      orangeColors: [
        '#EF8F40',
        'rgba(239,143,64,0.8)',
        'rgba(239,143,64,0.6)',
        'rgba(239,143,64,0.4)',
        'rgba(239,143,64,0.2)',
      ],
      barRate: 0.25,
      localDict: [],
      commonBarData: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow',
          },
          // formatter: '{b}: {c}次'
        },
        legend: {
          show: true,
          orient: 'horizontal',
          top: 'top',
          left: 'right',
          itemWidth: 9,
          itemHeight: 9,
          textStyle: {
            fontSize: '12',
            fontFamily: 'PingFangSC-Regular',
            color: '#6D7C8B',
          },
          data: [],
        },
        //color: ['#5192F4'],
        grid: {
          left: '50px',
          right: '20px',
          top: '30px',
          bottom: '20px',
        },
        xAxis: [
          {
            type: 'value',
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              rotate: 0,
              textStyle: {
                fontFamily: 'PingFangSC-Regular',
                fontSize: '12',
                color: '#526476',
              },
            },
            splitLine: {
              lineStyle: {
                // 使用深浅的间隔色
                color: ['#F5F7F8', '#E7EBEF'],
              },
            },
            max: 5,
          },
          {
            type: 'category',
            axisLine: { show: false },
            axisTick: { show: false },
            axisLabel: { show: false },
            splitArea: { show: false },
            splitLine: { show: false },
            data: [],
          },
        ],
        yAxis: [
          {
            type: 'category',
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              textStyle: {
                fontFamily: 'PingFangSC-Regular',
                fontSize: '12',
                color: '#526476',
              },
            },
            max: 5,
            data: [],
          },
          {
            type: 'category',
            axisLine: { show: false },
            axisTick: { show: false },
            axisLabel: { show: false },
            splitArea: { show: false },
            splitLine: { show: false },
            data: [],
          },
        ],
        series: [
          {
            type: 'bar',
            label: {
              normal: {
                show: false,
                position: 'right',
                formatter: '{d}%',
                color: '#419EFF',
              },
              emphasis: {
                show: false,
                textStyle: {
                  fontSize: '11',
                  fontWeight: 'bold',
                },
              },
            },
            labelLine: {
              normal: {
                show: false,
              },
            },
            data: [],
          },
        ],
      },
      commonBarOption: {},
    }
  },
  methods: {
    axisLabel(type) {
      let rotate = 0
      if (type === 'x') {
        rotate = this.componentData.xRotate
      } else if (type === 'y') {
        rotate = this.componentData.yRotate
      }
      return {
        rotate,
        textStyle: {
          fontFamily: 'PingFangSC-Regular',
          fontSize: '12',
          color: '#526476',
        },
        interval: 0,
      }
    },
    getCommonBarData(callback, newApi) {
      this.chartLoading = true
      let parseBarData = (data) => {
        let commonBarData = this.commonBarData
        if (!data.labelList) {
          data.labelList = []
        }
        commonBarData.legend.data = data.labelList
        if (
          JSON.stringify(data) === '{}' ||
          !data.valueList ||
          !data.valueList.length
        ) {
          if (!data.labelList || !data.labelList.length) {
            data.labelList = ['']
          }
          data.valueList = data.labelList.map((item) => [
            {
              //每条柱子的数据
              data: 0, //柱子长度
              name: '', //对应柱子上的label
              unit: '',
              label: '',
            },
          ]) //柱形图的数值，正常valueList长度为1，如果每个标签下有多条柱形图可添加
        }

        if (
          !data.valueList[0] ||
          (!data.valueList[0].length && !data.valueList[0])
        ) {
          data.valueList[0] = [{ data: 0, name: '', unit: '', label: '' }]
          for (let i = 1; i < data.valueList.length; i++) {
            if (data.valueList[i].length) {
              data.valueList[0] = data.valueList[i].map((item) => {
                return [{ data: 0, name: '', unit: '', label: '' }]
              })
            }
          }
        } else {
          delete commonBarData.yAxis[0].max
          delete commonBarData.xAxis[0].max
        }
        if (!this.componentData.seriesStackList || newApi) {
          let seriesStackList = []
          data.valueList.forEach((item) => {
            seriesStackList.push('')
          })
          this.componentData['seriesStackList'] = seriesStackList
          this.$emit( 'changeBarSeriesStackList', seriesStackList)
        } else {
          this.seriesStackList = this.componentData.seriesStackList
        }
        // let labelOption=this.componentData.series[0].label
        if (!Array.isArray(this.componentData.series[0].label)) {
          let label = []
          data.valueList.forEach((item) => {
            label.push(_.cloneDeep(this.componentData.series[0].label))
          })
          this.componentData.series[0].label = label
        }
        if (
          !this.componentData.series[0].label ||
          !this.componentData.series[0].label.length ||
          newApi
        ) {
          let labelList = []
          data.valueList.forEach((item) => {
            labelList.push({
              normal: {
                show: false,
                position: 'top',
                color: 'rgba(109,124,139,1)',
              },
            })
          })
          this.componentData.series[0]['label'] = labelList
          this.$emit( 'changeBarLabelList', labelList)
        }
        let xData = data.valueList[0].map((item) => item.name)
        let yData = data.valueList
        let type = this.componentData.barType || 'row'
        commonBarData.yAxis[0].data = null
        commonBarData.xAxis[0].data = null
        let unit = ''
        try {
          unit = data.valueList[0][0].unit
        } catch (e) {}
        this.unit = unit
        let isNameUnit = this.componentData.nameUnit || false
        if (type == 'row') {
          commonBarData.xAxis[0].type = 'value'
          if (isNameUnit) {
            commonBarData.xAxis[0].axisLabel = this.axisLabel('x')
            commonBarData.xAxis[0].name = '单位：' + unit
          } else {
            commonBarData.xAxis[0].axisLabel = {
              formatter: '{value}' + (unit || ''),
            }
            commonBarData.xAxis[0].axisLabel = {
              ...commonBarData.xAxis[0].axisLabel,
              ...this.axisLabel('x'),
            }
            commonBarData.xAxis[0].name = null
          }

          commonBarData.yAxis[0].axisLabel = this.axisLabel('y')
          commonBarData.yAxis[0].type = 'category'
          commonBarData.yAxis[0].data = xData
        } else {
          if (isNameUnit) {
            commonBarData.yAxis[0].axisLabel = this.axisLabel('y')
            commonBarData.yAxis[0].name = '单位：' + unit
          } else {
            commonBarData.yAxis[0].name = null
            commonBarData.yAxis[0].axisLabel = {
              formatter: '{value}' + (unit || ''),
            }
            commonBarData.yAxis[0].axisLabel = {
              ...commonBarData.yAxis[0].axisLabel,
              ...this.axisLabel('y'),
            }
          }
          commonBarData.xAxis[0].axisLabel = this.axisLabel('x')
          commonBarData.yAxis[0].type = 'value'
          commonBarData.xAxis[0].type = 'category'
          commonBarData.xAxis[0].data = xData
        }
        commonBarData.tooltip.formatter = function (param) {
          let str = ''
          if (param.length > 0) {
            str = param[0].axisValue + '<br/>'
          }
          for (let i = 0; i < param.length; i++) {
            str =
              str +
              param[i].marker +
              (data.labelList && data.labelList[i]
                ? param[i].seriesName + ' : '
                : '') +
              param[i].value +
              (unit || '') +
              '<br/>'
          }
          return str
        }
        commonBarData.series = yData.map((item, i) => ({
          type: 'bar',
          name: data.labelList ? data.labelList[i] || '' : null,
          yAxisIndex: i > 0 && this.componentData.isOverlab ? 1 : undefined,
          barMaxWidth: '29',
          labelLine: {
            normal: {
              show: false,
            },
          },
          data: item.map((item) => ({
            value: item.data,
            name: item.name,
            label: {
              normal: {
                show: false,
                position: 'top',
                color: 'rgba(109,124,139,1)',
                formatter: item.label || '{c}',
              },
            },
            itemStyle: {
              normal: {},
            },
          })),
        }))
        this.chartLoading = false
        if (!this.isDataReady) {
          this.isDataReady = true
          this.$emit( 'dataReady')
        }
      }
      if (!this.api || !this.api.reqUrl) {
        let data = {
          labelList: ['数据1', '数据2'],
          valueList: [
            //柱形图的数值，正常valueList长度为1，如果每个标签下有多条柱形图可添加
            [
              {
                //每条柱子的数据
                data: 1, //柱子长度
                name: '示例数据1', //对应柱子上的label
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 2,
                name: '示例数据2',
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 3,
                name: '示例数据3',
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 2,
                name: '示例数据4',
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 4,
                name: '示例数据5',
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 5,
                name: '示例数据6',
                label: '{c}', //柱子上的label formatter值
              },
            ],
            [
              {
                //每条柱子的数据
                data: 1, //柱子长度
                name: '示例数据1', //对应柱子上的label
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 2,
                name: '示例数据2',
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 3,
                name: '示例数据3',
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 2,
                name: '示例数据4',
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 4,
                name: '示例数据5',
                label: '{c}', //柱子上的label formatter值
              },
              {
                data: 5,
                name: '示例数据6',
                label: '{c}', //柱子上的label formatter值
              },
            ],
          ],
        }
        parseBarData(data)
        if (callback) {
          callback()
        }
      } else {
        nt.doRequest({
          method: 'post',
          uri: '/paas/chart-layout/v1/compdsconfig/testCompDSConfig',
          data: parseApi({
            api: this.api,
            time: this.time,
            mixinParam: this.mixinParam,
          }),
          onSuccess: (resp) => {
            let data =
              resp.data.content && resp.data.content.content
                ? resp.data.content.content
                : {}
            parseBarData(data)
            if (callback) {
              callback()
            }
          },
          onError: () => {
            this.chartLoading = false
            parseBarData({})
            if (callback) {
              callback()
            }
          },
        })
      }
    },
    changeStyle() {
      let commonBarData = this.commonBarData
      let componentData = this.componentData
      commonBarData.xAxis[0].show = componentData.xAxis.show
      commonBarData.yAxis[0].minInterval = componentData.splitInt ? 1 : 0
      commonBarData.xAxis[0].minInterval = componentData.splitInt ? 1 : 0
      commonBarData.grid = componentData.grid
      commonBarData.color = componentData.color

      let unit = this.unit
      let isNameUnit = this.componentData.nameUnit || false

      //XY轴交换数值

      if (componentData.barType === 'row') {
        if (commonBarData.yAxis[0].type === 'value') {
          ;[commonBarData.yAxis, commonBarData.xAxis] = [
            commonBarData.xAxis,
            commonBarData.yAxis,
          ]
        }
        //翻转操作
        if (componentData.isReverse && !this.isReverse) {
          commonBarData.yAxis.forEach((item) => {
            item.data.reverse()
          })
        } else if (!componentData.isReverse && this.isReverse) {
          commonBarData.yAxis.forEach((item) => {
            item.data.reverse()
          })
        }
      } else {
        if (commonBarData.xAxis[0].type === 'value') {
          ;[commonBarData.yAxis, commonBarData.xAxis] = [
            commonBarData.xAxis,
            commonBarData.yAxis,
          ]
        }
        //翻转操作
        if (componentData.isReverse && !this.isReverse) {
          commonBarData.xAxis.forEach((item) => {
            item.data.reverse()
          })
        } else if (!componentData.isReverse && this.isReverse) {
          commonBarData.xAxis.forEach((item) => {
            item.data.reverse()
          })
        }
      }

      //翻转操作
      if (componentData.isReverse && !this.isReverse) {
        this.isReverse = true
        commonBarData.series.forEach((serItem, serIndex) => {
          serItem.data.reverse()
        })
      } else if (!componentData.isReverse && this.isReverse) {
        this.isReverse = false
        commonBarData.series.forEach((serItem, serIndex) => {
          serItem.data.reverse()
        })
      }
      //渐变色操作
      const getOpacity = function (colorStr, index, length) {
        if (length === 1) return colorStr
        const FINAL_OPACITY = 0.25 //最后一个透明度0.25
        let opacity = 1
        // colorStr='rgba(239,143,64,0.8)'//colorStr
        let arr = colorStr.split(',')
        arr.length > 3 && (opacity = parseFloat(arr[3]))
        let colorCha = (opacity - FINAL_OPACITY) / (length - 1)
        if (componentData.gradientDire) {
          opacity = opacity - colorCha * index
        } else {
          opacity = FINAL_OPACITY + colorCha * index
        }

        if (arr.length > 3) {
          arr[3] = opacity + ')'
        } else {
          arr[2] = arr[2].substr(0, arr[2].length - 1) + opacity + ')'
        }
        return arr.join(',')
      }
      let label = componentData.series[0].label
      if (componentData.gradient) {
        commonBarData.series.forEach((serItem, serIndex) => {
          serItem.barGap = componentData.series[0].barGap
          serItem.data.forEach((dataItem, dataIndex) => {
            dataItem.label.normal.show = label[serIndex].normal.show
            dataItem.label.normal.color = label[serIndex].normal.color
            dataItem.label.normal.position = label[serIndex].normal.position
            dataItem.itemStyle.normal.color = getOpacity(
              componentData.color[serIndex % componentData.color.length],
              dataIndex,
              serItem.data.length
            )
          })
        })
      } else {
        commonBarData.series.forEach((serItem, serIndex) => {
          serItem.barGap = componentData.series[0].barGap
          serItem.data.forEach((dataItem, dataIndex) => {
            if (!dataItem.label) dataItem.label = { normal: {} }
            dataItem.label.normal.show = label[serIndex].normal.show
            dataItem.label.normal.color = label[serIndex].normal.color
            dataItem.label.normal.position = label[serIndex].normal.position
            dataItem.itemStyle.normal.color =
              componentData.color[serIndex % componentData.color.length]
          })
        })
      }
      //单位操作
      if (isNameUnit && unit) {
        if (commonBarData.yAxis[0].type == 'value') {
          delete commonBarData.xAxis[0].name
          commonBarData.yAxis[0].name = '单位：' + unit
        } else {
          delete commonBarData.yAxis[0].name
          commonBarData.xAxis[0].name = '单位：' + unit
        }
        delete commonBarData.yAxis[0].axisLabel
        commonBarData.xAxis[0].axisLabel = this.axisLabel('x')
      } else {
        if (commonBarData.yAxis[0].type == 'value') {
          commonBarData.yAxis[0].axisLabel = {
            formatter: '{value}' + (unit || ''),
            rotate: componentData.yRotate,
            interval: 0,
          }
          commonBarData.xAxis[0].axisLabel = this.axisLabel('x')
          commonBarData.xAxis[0].axisLabel.rotate = componentData.xRotate
        } else {
          commonBarData.xAxis[0].axisLabel = {
            formatter: '{value}' + (unit || ''),
            rotate: componentData.xRotate,
            interval: 0,
          }
          delete commonBarData.yAxis[0].axisLabel
          commonBarData.yAxis[0].axisLabel = {
            rotate: componentData.yRotate,
            interval: 0,
          }
        }
        delete commonBarData.xAxis[0].name
        delete commonBarData.yAxis[0].name
      }

      //柱形重叠操作
      if (componentData.isOverlap && commonBarData.series[1]) {
        if (componentData.barType === 'row') {
          commonBarData.yAxis[1].data = commonBarData.yAxis[0].data
          commonBarData.series[1].xAxisIndex = 0
          commonBarData.series[1].yAxisIndex = 1
        } else {
          commonBarData.xAxis[1].data = commonBarData.xAxis[0].data
          commonBarData.series[1].yAxisIndex = 0
          commonBarData.series[1].xAxisIndex = 1
        }
      } else {
        if (commonBarData.series[1]) {
          commonBarData.series[1].yAxisIndex = 0
          commonBarData.series[1].xAxisIndex = 0
        }
      }

      if (componentData.seriesStackList) {
        commonBarData.series.forEach((item, i) => {
          item.stack = componentData.seriesStackList[i]
        })
      }
      commonBarData.yAxis[0].axisLine = {
        show: false,
      }
      commonBarData.xAxis[0].axisLine.show = componentData.xAxis.axis.show
      for (let key in componentData.legend) {
        if (componentData.legend.hasOwnProperty(key)) {
          commonBarData.legend[key] = componentData.legend[key]
        }
      }
      commonBarData.yAxis[0].show = componentData.yAxis.show
      this.commonBarOption = _.cloneDeep(commonBarData)
      if (componentData.code) {
        //给开发人员测试的，怕忘记删，生产环境就不打印了
        process.env.NODE_ENV === 'development' &&
          console.log(this.mainTitle + ' 混入前option', commonBarData)
        this.commonBarOption = mixinOption(
          this.commonBarOption,
          componentData.code
        )
        process.env.NODE_ENV === 'development' &&
          console.log(this.mainTitle + ' 混入后option', this.commonBarOption)
      }
      if (this.$refs.barChart) {
        this.$refs.barChart.resize()
      }
    },
    changeParam() {
      if (this.api) {
        this.isReverse = false
        this.getCommonBarData(this.changeStyle)
        clearInterval(this.comInterval)
        if (this.interval) {
          this.isReverse = false
          this.comInterval = setInterval(() => {
            this.getCommonBarData(this.changeStyle)
          }, this.interval * 1000)
        }
      }
    },
  },
  watch: {
    componentData() {
      this.changeStyle()
    },
    'api.dsName': function () {
      this.getCommonBarData(this.changeStyle, true)
    },
    time() {
      let int = 0
      int = setInterval(() => {
        if (!this.chartLoading) {
          clearInterval(int)
          this.changeParam()
        }
      }, 50)
    },
    changeSize() {
      this.$refs.barChart.resize()
    },
    mixinParam: {
      handler: function (val, oldVal) {
        let int = 0
        int = setInterval(() => {
          if (!this.chartLoading) {
            clearInterval(int)
            this.changeParam()
          }
        }, 50)
      },
      deep: true,
    },
  },
  created() {
    this.getCommonBarData(this.changeStyle, true)
    if (this.interval) {
      this.comInterval = setInterval(() => {
        this.getCommonBarData(this.changeStyle)
      }, this.interval * 1000)
    }
  },
  beforeDestroy() {
    clearInterval(this.comInterval)
  },
  emits: ['changeBarSeriesStackList', 'changeBarLabelList', 'dataReady'],
}
</script>

<style scoped>
.line-row {
  width: 100%;
  height: 100%;
}
.chart-box {
  width: 100%;
  height: 100%;
  position: relative;
}
.operatorBtn {
  position: absolute;
  top: -50px;
  right: 20px;
  width: 30px;
  height: 20px;
  font-size: 14px;
  font-family: PingFangSC-Medium;
  color: #419eff;
  line-height: 20px;
}
</style>
